using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using BlogEngine.Core;


public partial class admin_Pages_Categories : System.Web.UI.Page
{
    Guid id = Guid.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(Request.QueryString["id"]) && Request.QueryString["id"].Length == 36)
        {
            id = new Guid(Request.QueryString["id"]);
        }

        if (!Page.IsPostBack && !Page.IsCallback)
        {
            BindData(id);
        }

        grid.RowDeleting += new GridViewDeleteEventHandler(grid_RowDeleting);
        btnAdd.Click += new EventHandler(btnAdd_Click);
        btnAdd.Text = id == Guid.Empty ? Resources.labels.add : Resources.labels.update;
        valExist.ServerValidate += new ServerValidateEventHandler(valExist_ServerValidate);
        Page.Title = Resources.labels.categories;
    }

    private void valExist_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;

        foreach (Category cat in Category.Items)
        {
            if (cat.Id != id && cat.Title.Equals(txtTitle.Text.Trim(), StringComparison.OrdinalIgnoreCase))
                args.IsValid = false;
            if (cat.Id != id && cat.Slug.Equals(txtSlug.Text.Trim(), StringComparison.OrdinalIgnoreCase))
                args.IsValid = false;
        }
    }

    void btnAdd_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Category cat;
            if (Request.QueryString["id"] != null)
                cat = BlogEngine.Core.Category.GetById(new Guid(Request.QueryString["id"]));
            else
                cat = new Category();

            cat.Title = txtTitle.Text;
            cat.Slug = txtSlug.Text;
            cat.Description = txtDescription.Text;
            cat.Order = int.Parse(txtOrder.Text);

            if (ddlParent.SelectedIndex != 0)
                cat.Parent = new Guid(ddlParent.SelectedValue);
            else
                cat.Parent = Guid.Empty;

            cat.Save();

            Response.Redirect(Request.Path, true);
        }
    }

    void grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Guid id = (Guid)grid.DataKeys[e.RowIndex].Value;
        Category cat = Category.GetById(id);

		// Removes all references to the category
		foreach (Post post in Post.Items)
		{
			if (post.Categories.Contains(cat))
			{
				post.Categories.Remove(cat);
			}
		}

		cat.Delete();
        cat.Save();
        Response.Redirect(Request.Path, true);
    }

    private void BindData(Guid categoryId)
    {
        BindCategory(categoryId);
        BindParents(categoryId);
        BindGrid();
    }

    private void BindCategory(Guid categoryId)
    {
        BlogEngine.Core.Category cat = new Category();
        
        if (categoryId != Guid.Empty)
        {
            BlogEngine.Core.Category tempCat = BlogEngine.Core.Category.GetById(categoryId); 

            if (tempCat != null)
                cat = tempCat;
        }

        txtTitle.Text = cat.Title;
        txtSlug.Text = cat.Slug;
        txtDescription.Text = cat.Description;
        txtOrder.Text = cat.Order.ToString();
    }

    private void BindGrid()
    {
        grid.DataKeyNames = new string[] { "Id" };
        grid.DataSource = Category.Items;
        grid.DataBind();
    }

    private void BindParents(Guid categoryId)
    {
        foreach (Category cat in Category.Items)
        {
            if (categoryId != cat.Id)
                ddlParent.Items.Add(new ListItem(cat.Title, cat.Id.ToString()));
        }

        ddlParent.Items.Insert(0, "-- " + Resources.labels.noParent + " --");

        if (categoryId != Guid.Empty)
        {
            Category parent = Category.GetById(categoryId);
            if (parent != null)
                ddlParent.SelectedValue = parent.Parent.ToString();
        }
    }

}
